package com.xxxx.crm.interceptor;

import com.xxxx.crm.dao.UserMapper;
import com.xxxx.crm.exceptions.NoLoginException;
import com.xxxx.crm.utils.LoginUserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author:王亚栋
 * @Date:2022/12/19 15:47
 * @Version:1.0
 */
public class NoLoginInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private UserMapper userMapper;

    /**
     * 拦截用户是否是登录状态
     * 在目标方法执行前执行的方法
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 获取cookie中的用户id
        Integer userId = LoginUserUtil.releaseUserIdFromCookie(request);

        if (userId == null || userMapper.selectByPrimaryKey(userId) == null){

            //抛出登录异常
            throw new NoLoginException();
        }
        return true;
    }
}
